package com.csap.framework.oauth2.example;


import cn.dev33.satoken.LoginUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.alibaba.fastjson.JSONObject;
import com.csap.framework.annotation.ResponseAdvice;
import com.csap.framework.extension.result.ResultParam;
import com.csap.framework.extension.result.ResultUtil;
import com.csap.framework.oauth2.client.Oauth2ClientProperties;
import com.ejlchina.data.TypeRef;
import com.ejlchina.okhttps.OkHttps;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 示例
 *
 * @author ycf
 */
@RestController
@ResponseAdvice
public class SampleController {
    /**
     * 客户端配置
     */
    @Resource
    private Oauth2ClientProperties oauth2ClientPropertiesa;

    @GetMapping("get")
    public String get() {
        return "124";
    }

    @GetMapping("get2")
    public String get2() {
        return "124";
    }

    @GetMapping("get3")
    public String get3() {
        return "124";
    }

    // 根据Code码进行登录，获取 Access-Token 和 openid
    @RequestMapping("/codeLogin")
    public ResultParam codeLogin(String code) {
        // 调用Server端接口，获取 Access-Token 以及其他信息
        JSONObject so = OkHttps.sync(oauth2ClientPropertiesa.getOauth2ServerUrl() + "/oauth2/token")
                .addBodyPara("grant_type", "authorization_code")
                .addBodyPara("code", code)
                .addBodyPara("client_id", oauth2ClientPropertiesa.getClientId())
                .addBodyPara("client_secret", oauth2ClientPropertiesa.getClientSecret())
                .post()
                .getBody()
                .toBean(new TypeRef<>() {
                });
        System.out.println("返回结果: " + so);

        // code不等于200  代表请求失败
        if (so.getInteger("code") != 0) {
            return ResultUtil.error("400", so.getString("msg"));
        }

        // 根据openid获取其对应的userId
        JSONObject data = so.getJSONObject("data");
        long uid = getUserIdByOpenid(data.getString("openid"));
        data.put("uid", uid);
        // 返回相关参数
        StpUtil.login(data.getString("loginId"));
        return ResultUtil.success(data);
    }

    // ------------ 模拟方法 ------------------
    // 模拟方法：根据openid获取userId
    private long getUserIdByOpenid(String openid) {
        // 此方法仅做模拟，实际开发要根据具体业务逻辑来获取userId
        return 10001;
    }

    // 模式三：密码式-授权登录
    @RequestMapping("/passwordLogin")
    public ResultParam passwordLogin(String username, String password) {
        // 模式三：密码式-授权登录
        JSONObject so = OkHttps.sync(oauth2ClientPropertiesa.getOauth2ServerUrl() + "/oauth2/token")
                .addUrlPara("grant_type", "password")
                .addUrlPara("client_id", oauth2ClientPropertiesa.getClientId())
                .addUrlPara("platform", oauth2ClientPropertiesa.getPlatform())
                .addUrlPara("username", username)
                .addUrlPara("password", password)
                .get()
                .getBody()
                .toBean(new TypeRef<>() {
                });
        System.out.println("返回结果: " + so);
        // code不等于200  代表请求失败
        if (so.getInteger("code") != 0) {
            return ResultUtil.error(so.getString("code"), so.getString("msg"));
        }
        // 根据openid获取其对应的userId
        JSONObject data = so.getJSONObject("data");
        // 返回相关参数
        StpUtil.login(data.getString("loginId"));
        return ResultUtil.success(data);
    }

    /**
     * 进入首页
     *
     * @param request request
     * @return
     */
    @RequestMapping("/index")
    public ModelAndView index(HttpServletRequest request) {
        request.setAttribute("uid", LoginUtil.getInstance().getLoginIdDefaultNull());
        return new ModelAndView("index.html");
    }
}
